const express = require('express')
const app = express()

const http = require('http').createServer(app)

const io = require('socket.io')(http);

var socket_list = []

io.on('connection',(socket)=>{
	console.log('用户连接了')
	let nickname = socket.handshake.query.nickname
	
	socket_list.push({
		user:nickname,
		'socket':socket
	})
	
	const users = socket_list.map(item=>{
		return{
			user:item.user
		}
	})
	socket.broadcast.emit('userlistlogin',users)
	
	socket.on('connection',(msg)=>{
		socket.broadcast.emit('siliao',{
			msg,
			nickname
		}) //这个是广播发送
	})
	
	// socket.on('loginchat',(msg)=>{
	// 	test()
	// })
	
	socket.on('only',(data)=>{//私聊返回的对象
		const {user,msg} = data
		let client = socket_list.find(item=>item.user == user)
		if(client){
			client.socket.emit('onlyyou',{
				who:nickname,
				user,
				msg
			})
		}
		
	})
	
	
	
	socket.on('disconnect',()=>{
		console.log('用户断开连接了')
		socket_list = socket_list.filter(item=>item.user !== nickname)
		console.log(socket_list.length)
	})
})


app.use('/',express.static('public'))

http.listen(4399,()=>{
	console.log('服务器连接成功')
})
